/// require dependent packages
/// params : mergeParams ( 合并参数 )
const express = require("express");
const mongoose = require("mongoose");
const jwt = require("jsonwebtoken");
const router = express.Router({
  mergeParams: true,
});

// userId: { type: String },
// title: { type: String },
// desc: { type: String },
// tags: [{ type: String }],
// content: { type: String },

// articleForm: {
//   title: "",
//   desc: "",
//   content: "",
//   tags: [],
// },

const Discussion = require("../../models/Discussion");

// 添加讨论
router.post("/discussion", async (req, res, next) => {
  const _model = req.body;
  const token = (req.headers.authorization || "").split(" ").pop();
  const { id } = jwt.verify(token, req.app.get("secret"));
  _model.userId = id;
  const model = await Discussion.create(_model);
  res.send({
    message: "保存成功",
    model: model,
  });
});

// 搜索讨论
router.get("/discussion/search", async (req, res) => {
  const searchKey = req.query.searchKey;
  var re = new RegExp(searchKey, "i");
  const model = await Discussion.where({ title: re }).find().limit(10);
  res.send({
    searchKey,
    searchVal: model,
  });
});

// 用户帖子
router.get("/discussion/user/:userId", async (req, res) => {
  const userId = req.params.userId;
  const model = await Discussion.where({ userId: userId }).find().limit(10);
  res.send(model);
});

// 查询讨论
router.get("/discussion", async (req, res) => {
  // 获取参数
  // console.log(req.query);
  const currentPage = req.query.currentPage ? Number(req.query.currentPage) : 1;
  const pageSize = req.query.pageSize ? Number(req.query.pageSize) : 10;
  // -1 latest in first
  const orderByTime = Number(req.query.orderByTime) == 1 ? 1 : -1;
  const searchKey = req.query.searchKey;
  // const searchKey = "";

  var re = new RegExp(searchKey, "i");

  matchOptions = { title: re };
  var model = await Discussion.aggregate([
    {
      $sort: {
        updatedAt: orderByTime,
      },
    },
    {
      $match: matchOptions,
    },
    // {
    //   $lookup: {
    //     from: "categories",
    //     localField: "categories",
    //     foreignField: "_id",
    //     as: "categories",
    //   },
    // },
    // {
    //   $addFields: {
    //     followCount: 0,
    //     signCount: 0,
    //     commitsCount: 0,
    //   },
    // },
    {
      $skip: (currentPage - 1) * pageSize,
    },
    {
      $limit: pageSize,
    },
  ]);

  res.send({
    model: model,
  });
});

module.exports = router;
